package com.ly.drivingschool.controller;

import com.ly.drivingschool.common.ResponseMessage;
import com.ly.drivingschool.pojo.Tweet;
import com.ly.drivingschool.service.TweetService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * 图片文件资源上传下载
 */
@RestController
public class UploadController {

    @Autowired
    private TweetService tweetService;

    // 图片路径
    String sowingImg = null;

    @PostMapping("uploadImg")
    public ResponseMessage uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //获取的文件名
        String fileName;
        //获取的文件拓展名
        String fileHzm;
        //定义文件上传的路径
        String filePath;
        //新文件名 以pId命名
        fileName = UUID.randomUUID().toString().replaceAll("-","");;

        //获取文件拓展名 idea中运行
        fileHzm = FilenameUtils.getExtension (file.getOriginalFilename ());

        // 获取文件资源路径 idea中运行
        filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/adminView/img/tweLeadImg/";
        System.out.println("获取的路径"+filePath);
        //创建文件对象
        File fileUrl = new File (filePath);
        System.out.println("文件路径："+fileUrl);

        //创建文件路径
        fileUrl.mkdirs ();

        //以绝对路径保存重命名后的图片
        file.transferTo (new File (filePath + "\\" + fileName + "." + fileHzm));

        //设置数据库保存路径
        sowingImg = "http://localhost:8084" + "/adminView/img/tweLeadImg/" + fileName + "." + fileHzm;
        System.out.println(sowingImg);

        // 将路径入库
        return ResponseMessage.createBySuccess();
    }
    // 这里保存数据 并将路径保存进去
    @PostMapping("saveTweet")
    public ResponseMessage saveTweet(@RequestBody Tweet tweet){
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String createTime = df.format(calendar.getTime());

        tweet.setTweIssueTime(createTime);
        tweet.setTweBrowseNum("0");
        tweet.setTweLeadImg(sowingImg);

        // 添加
        int code = tweetService.insertSelective(tweet);
        return ResponseMessage.createBySuccess();
    }
}
